package com.sg.business.work.view;

import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;

import com.mobnut.commons.util.Utils;
import com.sg.business.model.Work;
import com.sg.widgets.part.view.TreeNavigator;
import com.sg.widgets.registry.config.ColumnConfigurator;
import com.sg.widgets.viewer.CTreeViewer;

public class MyWork extends TreeNavigator {

	@Override
	public void createPartControl(Composite parent) {
		super.createPartControl(parent);

		addTreeHeadControl();
	}

	private void addTreeHeadControl() {
		final CTreeViewer treeViewer = (CTreeViewer) getNavigator()
				.getViewerControl().getViewer();
		final Tree tree = treeViewer.getTree();
		ScrollBar vb = tree.getVerticalBar();
		vb.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				TreeItem ti = tree.getTopItem();
				if(ti != null){
					Work work = (Work) ti.getData();
					if(work.isProjectWBSRoot()){
						setHeaderTo(treeViewer, null);
					}else if(work.isStandloneWork()){
						setHeaderTo(treeViewer, null);
					}else{
						setHeaderTo(treeViewer, ti);
					}
				} else {
					setHeaderTo(treeViewer, null);
				}
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
			}
		});
	}

	private void setHeaderTo(CTreeViewer treeViewer, TreeItem ti) {
		TreeColumn[] columns = treeViewer.getTree().getColumns();
		for (int i = 0; i < columns.length; i++) {
			String oldText = columns[i].getText();
			if (ti != null) {
				TreeItem rootTi = ti;
				while (rootTi.getParentItem() != null) {
					rootTi = rootTi.getParentItem();
				}
				String text = i == 0 ? Utils.getPlainText(rootTi.getText(i))
						: "";
				if (text != oldText) {
					columns[i].setText(text);
				}
			} else {
				ColumnConfigurator configurator = (ColumnConfigurator) columns[i]
						.getData("CONFIGURATOR");
				String text = configurator.getName();
				if (text != oldText) {
					columns[i].setText(text);
				}
			}
		}
	}
}
